namespace Chaliy.Syndication.UnitTests
{
	using System.Xml.XPath;
	using Xunit;
    using System.Xml;
    using System.Text;
	
	internal static class XmlAssertionExtensions
	{
        public static XPathNavigator ShouldMatch(this IXPathNavigable navigable, string xPath, string prefix, string namespaceUri, string message)
		{
            XPathNavigator result = EvaluteXPath(navigable, xPath, prefix, namespaceUri);
			if (result == null)
			{
                string assertMessage = BuildXPathAsserExceptionMessage(navigable,
                    xPath, prefix, namespaceUri, message);

                throw new AssertException(assertMessage);
			}

            return result;
		}

        public static void ShouldNotMatch(this IXPathNavigable navigable, string xPath, string prefix, string namespaceUri, string message)
        {
            XPathNavigator result = EvaluteXPath(navigable, xPath, prefix, namespaceUri);
            if (result != null)
            {
                string assertMessage = BuildXPathAsserExceptionMessage(navigable,
                    xPath, prefix, namespaceUri, message);

                throw new AssertException(assertMessage);
            }
        }

        private static string BuildXPathAsserExceptionMessage(IXPathNavigable navigable, string xPath, string prefix, string namespaceUri, string message)
        {
            StringBuilder messageBuilder = new StringBuilder();

            messageBuilder.AppendLine(message);
            messageBuilder.AppendLine("XPath: " + xPath);
            messageBuilder.AppendLine("Prefix: " + prefix + ", Namespace: " + namespaceUri);
            messageBuilder.AppendLine("XML: " + navigable.CreateNavigator().InnerXml);

            return messageBuilder.ToString();
        }

        private static XPathNavigator EvaluteXPath(IXPathNavigable navigable, string xPath, string prefix, string namespaceUri)
        {
            XPathNavigator navigator = navigable.CreateNavigator();
            XmlNamespaceManager manager = new XmlNamespaceManager(navigator.NameTable);
            manager.AddNamespace(prefix, namespaceUri);
            XPathNavigator result = navigator.SelectSingleNode(xPath, manager);
            return result;
        }
	}
}
